require('dotenv').config();

//1.导入mysql2
const mysql = require("mysql2");

const pool = mysql.createPool({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_DATABASE,
});

const exec = (sql, params = []) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, conn) => {
      if (err) {
        console.log("连接数据库失败:" + err.message);
        reject(err.message);
      }

      conn.execute(sql, params, (err, result) => {
        if (err) {
          console.log("执行sql失败:" + err.message);
          reject(err.message);
        }
        resolve(result);
        //释放连接
        conn.release();
      });
    });
  });
};

module.exports = { exec };
